//
//  secondViewController.m
//  mac2
//
//  Created by 李劭华 on 2021/7/26.
//
#import "CustomCellView.h"

#import <Masonry/Masonry.h>
#import "TableerRow.h"
#import "fileModel.h"
#import "secondViewController+dateHandle.h"

#import "secondViewController.h"

#define MyTableCellViewDataType @"MyTableCellViewDataType"

static NSString *viewIdentifier = @"view_Identifier";

static NSString *column1_Identifier = @"column1_Identifier";
static NSString *column2_Identifier = @"column2_Identifier";
static NSString *column3_Identifier = @"column3_Identifier";
static NSString *column4_Identifier = @"column4_Identifier";
static NSString *column5_Identifier = @"column5_Identifier";
static NSString *column6_Identifier = @"column6_Identifier";

@interface secondViewController ()<NSTableViewDelegate,NSTableViewDataSource>
@property (nonatomic,strong) NSButton *firstBtn;
@property (nonatomic,strong) NSButton *secondBtn;

@property (nonatomic,strong) NSScrollView *scrollView;
@property (nonatomic,strong) NSTableView *tableView;
@property (nonatomic,strong) NSMutableArray *datArray;

@end

@implementation secondViewController
- (BOOL)isFlipped{
    return YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    
    self.view.wantsLayer = YES;
    self.view.layer = [CALayer layer];
    self.view.layer.backgroundColor = [NSColor whiteColor].CGColor;
    self.view.frame = self.rect;
    [self initDataSource];
    [self initUI];
}
-(void)initDataSource{
    self.datArray=[NSMutableArray arrayWithCapacity:0];
//    for (int i = 0; i<20; i++) {
//        fileModel *model = [[fileModel alloc]init];
//        model.icon =[[NSImage alloc]init];
//        model.name=@"";
//        model.fileType=@"";
//        model.size=@"";
//        model.CreationDate=@"";
//        model.ModificationDate=@"";
//        [self.datArray addObject:model];
//    }
    
}
-(void)initUI{
    [self.view addSubview:self.firstBtn];
    [self.firstBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(20);
        make.left.equalTo(self.view.mas_left).with.offset(15);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
        
    }];
    
    [self.view addSubview:self.secondBtn];
    [self.secondBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(20);
        make.left.equalTo(self.firstBtn.mas_right).with.offset(100);
        make.width.mas_equalTo(300);
        make.height.mas_equalTo(40);
    }];
    
    
    [self.view addSubview:self.scrollView];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.firstBtn.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    self.scrollView.contentView.documentView = self.tableView;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView.contentView);
        make.height.mas_equalTo(1000);
    }];
}
#pragma mark - 点击事件
-(void)touchBtn:(NSButton *)sender{
    NSLog(@"touchBtn---:%ld",(long)sender.tag);

    if (sender.tag ==100) {
        [self dismissViewController:self];
    }
    else
    {
        [self openUserDesktop:nil];
    }

   
    
}

-(IBAction)openUserDesktop:(id)sender{
//    system("open ~/Documents");
    NSOpenPanel *openPanel = [NSOpenPanel openPanel];
        [openPanel setPrompt: @"打开"];
    openPanel.allowsMultipleSelection = YES;
    openPanel.canChooseDirectories = YES;
    openPanel.canChooseFiles = YES;
//    openPanel.message = @"本应用需要访问该目录，请点击允许";
    openPanel.prompt =@"选择";
    openPanel.directoryURL = [[NSURL alloc]initFileURLWithPath:NSHomeDirectory()];
        openPanel.allowedFileTypes = [NSArray arrayWithObjects: @"txt", @"doc",@"png",@"pdf",@"JPG", nil];
        openPanel.directoryURL = nil;
        
        [openPanel beginSheetModalForWindow:[self.view window] completionHandler:^(NSModalResponse returnCode) {
            
            if (returnCode == 1) {
                NSLog(@"[openPanel URLs]--:%@",[openPanel URLs]);

                [[openPanel URLs] enumerateObjectsUsingBlock:^(NSURL * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSString *filePath = [obj path];
                    fileModel *model = [[fileModel alloc]init];
                    NSImage *img =  [[NSWorkspace sharedWorkspace] iconForFile:filePath];
                    model.icon = img;
                    NSLog(@"model.icon : %@",model.icon);
                    
                    
                    NSString *displayNameAtPath =[[NSFileManager defaultManager] displayNameAtPath:filePath];
                    model.name = displayNameAtPath;
                    NSLog(@"model.name : %@",model.name);
                    
                    NSString *appName;
                    NSString *fileType;
                    [[NSWorkspace sharedWorkspace] getInfoForFile: filePath application: &appName type: &fileType];
                    
                    model.fileType = fileType;
                    NSLog(@"appName : %@ , fileType : %@ , model.fileType : %@",appName,fileType,model.fileType);

                    NSDictionary *attributesOfItemAtPathDic = [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil];
                    NSLog(@"attributesOfItemAtPathDic--:%@",attributesOfItemAtPathDic);
                    model.size = [attributesOfItemAtPathDic objectForKey:@"NSFileSize"];
                    model.CreationDate = [self getStringFromDate:[attributesOfItemAtPathDic objectForKey:@"NSFileCreationDate"]];
                    model.ModificationDate = [self getStringFromDate:[attributesOfItemAtPathDic objectForKey:@"NSFileModificationDate"]];
                    NSLog(@"model.size--:%@",model.size);
                    NSLog(@"model.CreationDate--:%@",model.CreationDate);
                    NSLog(@"model.ModificationDate--:%@",model.ModificationDate);

                    [self.datArray addObject:model];
                }];
                [self.tableView reloadData];
            }
        }];
}

#pragma mark - 代理事件

-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    return self.datArray.count;
}

-(NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    CustomCellView *view = [tableView makeViewWithIdentifier:viewIdentifier owner:self];
    if (!view) {
        view = [[CustomCellView alloc]initWithFrame:CGRectZero];
        view.identifier = viewIdentifier;
    }
    
        if (row<self.datArray.count) {
            fileModel *model = self.datArray[row];
            if ([tableColumn.identifier isEqualToString:column1_Identifier]) {
                view.picImageView.image = model.icon;
//                view.picImageView.image = [NSImage imageNamed:@"planSelect"];
                view.titleLab.hidden=YES;
                view.imageView.hidden =NO;
            }
            else if ([tableColumn.identifier isEqualToString:column2_Identifier]) {
                view.imageView.hidden =YES;
                view.titleLab.hidden=NO;

                view.titleLab.stringValue = model.name;
            }
            else if ([tableColumn.identifier isEqualToString:column3_Identifier]) {
                view.imageView.hidden =YES;
                view.titleLab.hidden=NO;
                view.titleLab.stringValue = model.fileType;
            }
            else if ([tableColumn.identifier isEqualToString:column4_Identifier]) {
                view.imageView.hidden =YES;
                view.titleLab.hidden=NO;
                view.titleLab.stringValue = model.size;
            }
            else if ([tableColumn.identifier isEqualToString:column5_Identifier]) {
                view.imageView.hidden =YES;
                view.titleLab.hidden=NO;
                view.titleLab.stringValue = model.CreationDate;
            }
            else if ([tableColumn.identifier isEqualToString:column6_Identifier]) {
                view.imageView.hidden =YES;
                view.titleLab.hidden=NO;
                view.titleLab.stringValue = model.ModificationDate;
            }
        }
    
    return view;
}

////返回自定义的Cell实例
///*
//需要注意，这个方法在第一次调用的时候 tableColumu对象是nil 如果这时返回了Cell，则此Cell宽度会覆盖整个列表
//在使用时要多加注意
//*/
- (nullable NSCell *)tableView:(NSTableView *)tableView dataCellForTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row;
{
    if (tableColumn!=nil) {
        NSCell * cell = [[NSCell alloc]init];
        return cell;
    }
    return nil;
}
-(NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{
    TableerRow *rowView= [[TableerRow alloc]init];
    rowView.floating = YES;
    rowView.targetForDropOperation = YES;
    rowView.draggingDestinationFeedbackStyle = NSTableViewDraggingDestinationFeedbackStyleRegular;
    rowView.indentationForDropOperation = 100;
    return rowView;
}

-(void)tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
{
    NSLog(@"添加行是调用");
}
-(void)tableView:(NSTableView *)tableView didRemoveRowView:(NSTableRowView *)rowView forRow:(NSInteger)row
{
    NSLog(@"移除时回调");
}
//-(void)tableView:(NSTableView *)tableView willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
//{
//    NSTextField *_cell = cell;
//    _cell.textColor = [NSColor redColor];
//}
-(NSString *)tableView:(NSTableView *)tableView toolTipForCell:(NSCell *)cell rect:(NSRectPointer)rect tableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row mouseLocation:(NSPoint)mouseLocation
{
    if (row<self.datArray.count) {
        return self.datArray[row];
    }
    return @"";
}
-(BOOL)tableView:(NSTableView *)tableView shouldShowCellExpansionForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    return YES;
}
-(CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row{
    return 40;
}
//排序回调函数
-(void)tableView:(NSTableView *)tableView sortDescriptorsDidChange:(NSArray<NSSortDescriptor *> *)oldDescriptors{
    NSLog(@"排序回调函数%@",oldDescriptors[0]);
    if ([oldDescriptors[0] key] == column4_Identifier ) {
        NSArray *sortedArray = [self.datArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            fileModel *first = a;
            fileModel *second = b;
            if (oldDescriptors[0].ascending) {
                return [first.size compare:second.size];

            }
            else
            {
                return [second.size compare:first.size];

            }
        }];
        self.datArray = [NSMutableArray arrayWithArray:sortedArray];
        [self.tableView reloadData];
    }
    if ([oldDescriptors[0] key] == column5_Identifier ) {
        NSArray *sortedArray = [self.datArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            fileModel *first = a;
            fileModel *second = b;
            if (oldDescriptors[0].ascending) {
                return [first.CreationDate compare:second.CreationDate];
            }
            else
            {
                return [second.CreationDate compare:first.CreationDate];
            }
        }];
        self.datArray = [NSMutableArray arrayWithArray:sortedArray];
        [self.tableView reloadData];
    }
    if ([oldDescriptors[0] key] == column6_Identifier ) {
        NSArray *sortedArray = [self.datArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            fileModel *first = a;
            fileModel *second = b;
            if (oldDescriptors[0].ascending) {
                return [first.ModificationDate compare:second.ModificationDate];
            }
            else
            {
                return [second.ModificationDate compare:first.ModificationDate];
            }
        }];
        self.datArray = [NSMutableArray arrayWithArray:sortedArray];
        [self.tableView reloadData];
    }
}
#pragma mark - 拖拽排序
// drag operation stuff
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard
{
    // Copy the row numbers to the pasteboard.
//    NSData *zNSIndexSetData = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
    NSData *zNSIndexSetData =  [NSKeyedArchiver archivedDataWithRootObject:rowIndexes requiringSecureCoding:YES error:nil];
    [pboard declareTypes:[NSArray arrayWithObject:MyTableCellViewDataType] owner:self];
    [pboard setData:zNSIndexSetData forType:MyTableCellViewDataType];
    return YES;
}

- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)op
{
    // Add code here to validate the drop
    //NSLog(@"validate Drop");

    return NSDragOperationEvery;
}

- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info
      row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation
{
    NSPasteboard* pboard = [info draggingPasteboard];
    NSData* rowData = [pboard dataForType:MyTableCellViewDataType];
//    NSIndexSet* rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:rowData];
    NSIndexSet* rowIndexes = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSIndexSet class] fromData:rowData error:nil];
    NSInteger dragRow = [rowIndexes firstIndex];

        // Move the specified row to its new location...
        // if we remove a row then everything moves down by one
        // so do an insert prior to the delete
        // --- depends which way we're moving the data!!!
    if (dragRow < row) {
        [self.datArray insertObject:[self.datArray objectAtIndex:dragRow] atIndex:row];
        [self.datArray  removeObjectAtIndex:dragRow];
        [self.tableView noteNumberOfRowsChanged];
        [self.tableView reloadData];
        
        return YES;
        
    } // end if

    NSString * zData = [self.datArray objectAtIndex:dragRow];
    [self.datArray removeObjectAtIndex:dragRow];
    [self.datArray insertObject:zData atIndex:row];
    [self.tableView noteNumberOfRowsChanged];
    [self.tableView reloadData];

    return YES;
}
#pragma mark - ui
-(NSButton *)firstBtn
{
    if (!_firstBtn) {
        _firstBtn = [NSButton buttonWithTitle:@"返回" target:self action:@selector(touchBtn:)];
        _firstBtn.tag = 100;
    }
    return _firstBtn;
}
-(NSButton *)secondBtn
{
    if (!_secondBtn) {
        _secondBtn = [NSButton buttonWithTitle:@"选择文件 或者从 菜单栏 file->openUserDesktop" target:self action:@selector(touchBtn:)];
        _secondBtn.tag = 101;
    }
    return _secondBtn;
}
-(NSTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[NSTableView alloc]initWithFrame:CGRectZero];
        NSTableColumn *column1 =[[NSTableColumn alloc]initWithIdentifier:column1_Identifier];
        column1.title =@"icon";
        [_tableView addTableColumn:column1];
        
        NSTableColumn *column2 =[[NSTableColumn alloc]initWithIdentifier:column2_Identifier];
        column2.title =@"名称";

        [_tableView addTableColumn:column2];
        
        NSTableColumn *column3 =[[NSTableColumn alloc]initWithIdentifier:column3_Identifier];
        column3.title =@"格式";

        [_tableView addTableColumn:column3];

        NSTableColumn *column4 =[[NSTableColumn alloc]initWithIdentifier:column4_Identifier];
        column4.title =@"大小";

        [_tableView addTableColumn:column4];

        NSTableColumn *column5 =[[NSTableColumn alloc]initWithIdentifier:column5_Identifier];
        column5.title =@"创建时间";

        [_tableView addTableColumn:column5];

        NSTableColumn *column6 =[[NSTableColumn alloc]initWithIdentifier:column6_Identifier];
        column6.title =@"修改时间";
        [_tableView addTableColumn:column6];

        _tableView.delegate = self;
        _tableView.dataSource= self;
        
        [_tableView.tableColumns enumerateObjectsUsingBlock:^(NSTableColumn * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.identifier == column5_Identifier || obj.identifier == column6_Identifier) {
                obj.minWidth = 200;
            }
            else{
                obj.minWidth = 100;
            }
            obj.headerToolTip = [NSString stringWithFormat:@"鼠标放在第%lu列",(unsigned long)idx];
//            obj.sortDescriptorPrototype = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
            obj.sortDescriptorPrototype = [NSSortDescriptor sortDescriptorWithKey:obj.identifier ascending:NO];
        }];
        [_tableView registerForDraggedTypes:[NSArray arrayWithObject:MyTableCellViewDataType] ];

    }
    return _tableView;
}

-(NSScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[NSScrollView alloc]initWithFrame:CGRectZero];
        _scrollView.hasVerticalScroller = YES;
        _scrollView.hasHorizontalScroller = YES;
    }
    return _scrollView;
}
@end
